<template>
	<view class="u-page">
		<up-list v-if="listData.length > 0" :pagingEnabled="true" @scrolltolower="scrolltolower">
			<up-list-item v-for="(item, index) in listData" :key="`recommend_${index}`">
				<ListItem :item="item" :index="index" @setHandle="setHandle" />
			</up-list-item>
			<up-list-item>
				<up-loadmore line :status="isEnd ? 'nomore' : 'loadmore'"></up-loadmore>
			</up-list-item>
		</up-list>
		<up-empty v-else mode="search"></up-empty>
	</view>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch, toRaw, computed } from 'vue';
import API from '@/api/index.ts';
import ListItem from './components/list-item.vue';

defineOptions({
	name: 'SolverRecommendIndex'
});

const props = defineProps({
	searchValue: {
		type: String,
		default: ''
	}
});

// 列表数据
const listData = ref<API.RecommendResponse[]>([]);

// 分页
const pageOption = reactive({
	page: 1,
	size: 10
});

// 总共多少条数据
const total = ref(0);

// 拉到底端加载
const scrolltolower = () => {
	// 判断当前页码是否大于总页数
	if (isEnd.value) {
		return;
	}
	pageOption.page++;
	getList();
};

// 是否到底了
const isEnd = computed(() => {
	return pageOption.page > Math.ceil(total.value / pageOption.size);
});

// 获取数据
const getList = () => {
	API.recommend
		.queryRecommendList({
			page: pageOption.page,
			size: pageOption.size
			// searchValue: props.searchValue
		})
		.then((res) => {
			if (res.data) {
				listData.value = toRaw(listData.value).concat(res.data);
			}
			const pagination = res.pagination;
			total.value = pagination.total;
		});
};

// 点击点赞或者收藏
const setHandle = (data: changeHandleType) => {
	const { sign, handleSign, taskId } = data;
	const handleNum = handleSign === 'add' ? 1 : -1;
	for (let i = 0; i < listData.value.length; i++) {
		const item = listData.value[i];
		if (item.id === taskId) {
			item[sign] = !item[sign];
			if (sign === 'collected') {
				item.collectCounts += handleNum;
			} else {
				item.likeCounts += handleNum;
			}
			break;
		}
	}
};

// 监听搜索值
watch(
	() => props.searchValue,
	(newVal, oldVal) => {
		if (oldVal !== undefined) {
			// 如果搜索值发生变化，需要重置页码
			pageOption.page = 1;
			// 清空列表数据
			listData.value = [];
			// 重新获取数据
			getList();
		}
	},
	{
		deep: true,
		immediate: true
	}
);

onMounted(() => {
	// 如果搜索值发生变化，需要重置页码
	pageOption.page = 1;
	// 清空列表数据
	listData.value = [];
	getList();
});
</script>

<style></style>
